# wsc控制
import _thread
import random,time
from libs import northstar as ns
from libs import websocket as wss
ns.init_BUTTON()
ns.init_SCREEN()
ns.init_NETWORK()
ns.BUTTON_disible_btn=1

ws=wss.WebSocket(1)
@ws.onMessage
def om(data): # 数据处理
    if(data[0]=='B'): # button
        if data[1]=="U":
            flag=False
        elif data[1]=="D":
            flag=True
        if data[2]=="U":
            ns.BUTTON_btn_up=flag
        elif data[2]=="D":
            ns.BUTTON_btn_down=flag
        elif data[2]=="L":
            ns.BUTTON_btn_left=flag
        elif data[2]=="R":
            ns.BUTTON_btn_right=flag
        elif data[2]=="A":
            ns.BUTTON_btn_a=flag
        elif data[2]=="B":
            ns.BUTTON_btn_b=flag
        ws.sendMessage("Y")
    if(data[0]=='L'): # 命令执行
        exec(data[1:])
        ws.sendMessage("Y")
    else: # 未知命令
        ws.sendMessage("N"+"Unknow command")
@ws.onConnect
def om2(data): # 连接
    ws.sendMessage("C"+"Connect!")
port=random.randint(10000,30000) # 安全随机端口
def listen_btn(): # 监听准备
    print(port)
    ns.oled.fill(0)
    ns.oled.text("WSContorler mode",0,0)
    ns.oled.text("ip:",0,12)
    ns.oled.text("ws://"+ns.wifi.ifconfig()[0]+":",0,24)
    ns.oled.text(str(port),80,36)
    ns.oled.show()
    ws.listen(("0.0.0.0",port),True)

# 开线程
_thread.start_new_thread(listen_btn,())
time.sleep(10)
ns.oled.fill(1) # 隐藏
ns.oled.show()
from system_app import test_btn





